<?php
/**
 * YOS News Crawler Component
 *
 * @package		yos_news_crawler
 * @subpackage	CMS
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
JTable::addIncludePath(JPATH_COMPONENT_SITE.DS.'cms'.DS.'drupalpost'.DS.'tables');
require_once(JPATH_COMPONENT_SITE.DS.'helpers'.DS.'phpWebHacks.php');
class YOS_Cms_Drupalpost extends JObject {
	//object article
	private $_arr_article;
	
	public $_db		=	null;
	
	//store job id key
	private $_job_configuration;
	
	var $cms_config	=	array();
	
	public function __construct($job_configuration, $arr_article)
	{
		$this->_job_configuration = $job_configuration;
		$this->_arr_article = $arr_article;
		if (!$this->_db	=	$this->getDBO()) {
			return false;
		}
		$this->_get_cmsconfig();	
	}
			
	//when job call store_article function,
	//-store images file
	//-build Joomla article
	//-store in database
	
	function getDBO()
	{
		require(JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupalpost'.DS.'cms_config.php');		
		$option_ 	= array(); //prevent problems 
		$option_['driver']   = $d_w_driver;       	// Database driver name
		$option_['host']     = $d_w_host;    		// Database host name
		$option_['user']     = $d_w_user;  	    	// User for database authentication
		$option_['password'] = $d_w_password;  		// Password for database authentication
		$option_['database'] = $d_w_database;  	  	// Database name
		$option_['prefix']   = $d_w_prefix;          // Database prefix (may be empty)
		if (empty($option_['user']) || empty($option_['password']) || empty($option_['database']) || empty($option_['driver']) || empty($option_['host']))
		{
			$config	=	JFactory::getConfig();
			
			$option_['driver']   = $config->getValue('dbtype');       	// Database driver name
			$option_['host']     = $config->getValue('host');    		// Database host name
			$option_['user']     = $config->getValue('user');  	    	// User for database authentication
			$option_['password'] = $config->getValue('password');  		// Password for database authentication
			$option_['database'] = $config->getValue('db');  	  	// Database name
		}
		$db_	= &JDatabase::getInstance( $option_ );
		if (!empty($db_->message)) {
				$this->msg = JText::sprintf($db_->message);
				return false;
			}	
		$this->_dbo=$db_;
		return $this->_dbo;
	}
	public function store_articles()
	{
		$db	 =& JFactory::getDBO();
		
		
		$cms_params_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupalpost'.DS.'cms_config_job.xml';
		if(!is_readable($cms_params_file)){
			$this->setError('[CMS DRUPAL] unable to load params configure file: '.$cms_params_file);
			return false;
		}
		$params = new JParameter($this->_job_configuration->params, $cms_params_file);
		$time_plus = 0;
		
		// make browser object
/*		BEGIN MAKE	*/
			$browser = new phpWebHacks();
			$page =	$browser->get($params->get('page_login'));

			$action = '';
			$form_data = $browser->parseForm('user-login-form', $action);
			if (!$action)
			{
				$action = $params->get('page_login');
			}			
			if (!is_array($form_data) || !key_exists('name', $form_data) || !key_exists('pass', $form_data)) {
				
				
				$this->setError('[CMS DRUPAL] invalid form login: '. $params->get('page_login'));
				return false;
			}
			$query		=	"SELECT name FROM #__users WHERE uid=".	$params->get('author_by');
			$db_drupal	=	$this->getDBO();
			$db_drupal->setQuery($query);
			
			$name_author		=	$db_drupal->loadResult();
			$form_data['name']  =	$name_author;
			$form_data['pass']  =  	$params->get('password');	
		//	$form_data['pass']  =  	'abx';	
			
			$response = $browser->post($action, $form_data);
			
			if (preg_match('/<div\s*id="message">\s*<div\s*class="messages error">(.*?)<\/div>\s*<\/div>/ism',$response,$match)) {	
			
				$page_mess	=	preg_replace('/<a[^>]*>.*?<\/a>/','',$match[1]);
				$page_mess	=	preg_replace('/<p[^>]*>.*?<\/p>/','',$page_mess);
				$this->setError('[CMS DRUPAL] error login: '. $params->get('page_login')."\r\n\t\t message: $page_mess");
			}
/*			END MAKE	*/
			$query	=	'SELECT language FROM `__languages` WHERE enabled=1';
			$db_drupal->setQuery($query);
			$language	=	$db_drupal->loadResult();
/*			GET TERM*/
			$type		=	$params->get('type');
			$query	=	"SELECT  V.*
						FROM `#__vocabulary` as V, `#__vocabulary_node_types` as VNT
						WHERE V.vid=VNT.vid 
							AND VNT.type=".$db_drupal->Quote($type);
			$db_drupal->setQuery($query);
			$vocabularys	=	$db_drupal->loadObjectList();
			
			$term 				=	$params->get('term');
			$term_arr_config	=	explode(',',$term);
			$term_arr_post		=	array();
			$arr_delete			=	array();
			for ($i=0;$i<count($vocabularys);$i++)
			{
				$vocabulary	=	$vocabularys[$i];
				$query	=	"SELECT  TD.tid
						FROM `#__term_data` as TD, `#__vocabulary` as V
						WHERE TD.vid = V.vid
							AND V.vid=".$vocabulary->vid;
				$db_drupal->setQuery($query);
				$term_data	=	$db_drupal->loadResultArray();
				$term_config	=	array();
				for ($k=0;$k<count($term_arr_config);$k++)
				{
					if (in_array($term_arr_config[$k],$term_data)) {
						$term_config[] = $term_arr_config[$k];
					}
				}
				
				if ($vocabulary->tags) {
					$term_post	=	array();
//					$arr_delete[]		=	'taxonomy[tags][]';
					$term_post['name']	=	'taxonomy[tags]['.$vocabulary->vid.']';
					$query	=	"SELECT  TD.name
						FROM `#__term_data` as TD
						WHERE TD.tid in(".implode(',',$term_config).' )';
					$db_drupal->setQuery($query);
					$term_str	=	$db_drupal->loadResultArray();					
					$term_post['value']	=	implode(',',$term_str);
					array_push($term_arr_post,$term_post);
					continue;
				}
				
				if ($vocabulary->multiple) {
					$arr_delete[]		=	"taxonomy[$vocabulary->vid][]";					
					for ($j=0;$j<count($term_config);$j++)
					{
						$term_post	=	array();
						$term_post['name']	=	"taxonomy[$vocabulary->vid][$j]";
						$term_post['value']	=	$term_config[$j];
						array_push($term_arr_post,$term_post);

					}
					continue;
				}
				
				if (!($vocabulary->tags && $vocabulary->multiple)) {
					$term_post	=	array();					
					$term_post['name']	=	"taxonomy[$vocabulary->vid]";
					$term_post['value']	=	implode(',',$term_config);
					array_push($term_arr_post,$term_post);
					continue;
				}
			}
			
		foreach ($this->_arr_article as &$article){
			//check article link is exist			
			$query = "SELECT COUNT(*) FROM #__yos_content_link WHERE `link` = ".$db->Quote($article->link)." 
				AND `cms` = 'drupal'";
			$db->setQuery($query);
			$is_exist = $db->loadResult();
			if ($db->getErrorNum()) {
				$arr_error = debug_backtrace();
				$this->setError('[CMS DRUPAL] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
				return false;
			}
			if ($is_exist) {
				echo $article->link.' is exit'.'<br />';
				continue;
			}			
			$row = $this->_store_article($article, $params, $time_plus,$browser,$language,$term_arr_post,$arr_delete,$name_author);			
			if (!$row) {
				return false;
			}
			$time_plus = $time_plus + 10;
			if (!$row) {
				continue;
			}		
			
			$this->_added_fetched_article($article->link, $row);			
			$row_revisions 		=	JTable::getInstance('Node_revisions','Table');
			$row_revisions->bind($row);
			$row_revisions->store();
			
			//store image...
			if ($this->_job_configuration->get_img) {
				if($this->_move_image($article->image_path, $row_revisions)){
					//update article
					$dispatcher		= &JDispatcher::getInstance();
					JPluginHelper::importPlugin('content');				
					$result	= $dispatcher->trigger('onBeforeNodeRevisionsSave', array (&$row_revisions, false ));
					$row_revisions->store();					
					$result	= $dispatcher->trigger('onAfterNodeRevisionsSave', array (&$row_revisions, false ));
				}		
			}			
		}
	}
	
	private function _move_image($image_path, &$row){
		//TODO: get destination image path from cms configure here
		if (count($this->cms_config)==0) {
			$this->_get_cmsconfig();
		}
		$config	=	$this->cms_config;	
		$dest_img_path =$config['image_path_root'].DS.$row->nid;
		$new_img_base_url =$config['image_url_root'].'/'.$row->nid.'/';	
		
		if(!JFolder::create($dest_img_path)){
			$this->setError('[CMS DRUPAL] cannot create folder to store images: '.$dest_img_path);
			return false;
		}
		if (!is_writable($dest_img_path)) {
			$this->setError('[CMS DRUPAL] image path is not writable: '.$dest_img_path);
			return false;
		}		
		$row->teaser = $this->_move_image_in_string($row->teaser, $image_path, $dest_img_path, $new_img_base_url);
		$row->body = $this->_move_image_in_string($row->body, $image_path, $dest_img_path, $new_img_base_url);
		
		return true;
	}
	
	private function _move_image_in_string($str_in, $image_path, $dest_img_path, $new_img_base_url){
		if (!preg_match_all('/<img.*?src="([^"]+)"[^>]*>/ism', $str_in, $matches)) {
			return $str_in;
		}		
		foreach ($matches[1] as $str_img_src){
			$file_name = JFile::getName($str_img_src);
			$file_name = urldecode($file_name);
			if (!is_readable($image_path.DS.$file_name)) {
				continue;
			}
			if(!JFile::copy($image_path.DS.$file_name, $dest_img_path.DS.$file_name)){
				continue;
			}
			$str_in = str_replace($str_img_src, $new_img_base_url.$file_name, $str_in);
		}
		
		return $str_in;
	}
	
	//get cms configuration
	private function _get_cmsconfig()
	{
		if ($this->cms_config) {
			return $this->cms_config;
		}
		$config_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupalpost'.DS.'cms_config.php';
		if(!is_readable($config_file)){
			$this->setError('[CMS JOOMLA] unable to load configure file: '.$config_file);
			return false;
		}
		require($config_file);	
		$this->cms_config['image_path_root']	=	$image_path_root;
		$this->cms_config['image_url_root']		=	$image_url_root;
		return $this->cms_config;
	}			
	
	//store an article to database
	private function _store_article(&$obj_article, $params, $time_plus,$browser,$language,$term_arr_post,$arr_delete,$name_author)
	{
		$db	 =& $this->_db;	
		if (!$obj_article->full_text) {
			$obj_article->full_text	=$obj_article->intro_text;
		}
		// process title
		$db_drupal	=	$this->getDBO();
		$obj_article->title	=	str_replace('/\\r|\\n/','',htmlspecialchars($obj_article->title));
		$obj_article->title	=	str_replace("/\\r|\\n/",'',htmlspecialchars($obj_article->title));
		$obj_article->title	=	str_replace('\n','',$obj_article->title);
		$obj_article->title	=	str_replace('\r','',$obj_article->title);
		$obj_article->title	=	str_replace("\n",'',$obj_article->title);
		$obj_article->title	=	str_replace("\r",'',$obj_article->title);
	
		$query	=	'SELECT count(*) 
					FROM `#__node` 
					WHERE title='.$db_drupal->Quote($obj_article->title).'					
						AND uid='.$params->get('author_by');
		$db_drupal->setQuery($query);
		$query_title	=	$db_drupal->getQuery();
		if ($db_drupal->loadResult()) {
			$time_now		= JFactory::getDate();
			$time_now		= $time_now->toUnix() + $time_plus;//seconds
			$time_now		=	date('Y-m-d H-i-s',$time_now);
			$title			=	$obj_article->title;
			$obj_article->title	=	$obj_article->title	.' '.$time_now;
			$sdb	=	JRequest::getInt('showdebug',0);
				if ($sdb) {	
					echo ('[CMS DRUPAL] title is changed. bacause:  requires that the fields title, author are a unique combination '."\r\n".$title.'=>'.$obj_article->title);
				}
			
		}
		//add according info
		$str_source_content = $this->_job_configuration->according_to;
		//readmore (add original source link)		
		$obj_article->full_text =$obj_article->full_text."\n".'<p class="according">'.$str_source_content.'</p>';	
		
		//title ads
		if ($this->_job_configuration->title_ext) {
			if ($this->_job_configuration->title_ext_pos == 0) {
				$obj_article->title = $this->_job_configuration->title_ext . $obj_article->title;
			}
			else {
				$obj_article->title = $obj_article->title . $this->_job_configuration->title_ext;
			}			
		}		
		//intro ads
		if ($this->_job_configuration->ads) {
			if ($this->_job_configuration->catads == 0) {
				$obj_article->intro_text = $this->_job_configuration->ads . $obj_article->intro_text;
			}
			else {
				$obj_article->intro_text = $obj_article->intro_text . $this->_job_configuration->ads;
			}			
		}
		// 
			$page =	$browser->get($params->get('page_post'));
		
			$action = '';
			$form_data = $browser->parseForm('node-form', $action);
			
			if (!is_array($form_data) || !key_exists('body',$form_data)) {
				$this->setError('[CMS DRUPAL] invalid form post content: '.$params->get('page_post'));
				$sdb	=	JRequest::getInt('showdebug',0);
				if ($sdb) {					
					echo '<br /><hr />';
					var_dump($form_data);
					echo $page;				
				}
				return false;				
			}
			if (!$action)
			{
				$action = $params->get('page_post');
			}
			$time_now		= JFactory::getDate();
			$time_now		= $time_now->toUnix() + $time_plus;//seconds
			$time_now		=	date('Y-m-d',$time_now);
			
			$code_body		=	uniqid('YOS_DIRECTORY_SEPARATOR_');
			
			$form_data['title']					=	$obj_article->title;
			$form_data['teaser_js']				=	$obj_article->intro_text;
			$form_data['body']					=	$obj_article->full_text.$code_body;
			$form_data['teaser_include']		=	$params->get('summary');
			$form_data['format']				=	$params->get('input_format');
			$form_data['comment']				=	$params->get('comment_settings');
			$form_data['pathauto_perform_alias']=	1;
			$form_data['name']					=	$name_author;
			$form_data['status']				=	$params->get('published');
			$form_data['sticky']				=	$params->get('sticky_at');
			$form_data['promote']				=	$params->get('front_page');
			$form_data['comment']				=	$params->get('comment_settings');			

			for ($j	=	0;$j<count($arr_delete);$j++)
			{
				if (isset($form_data[$arr_delete[$j]])) {
					unset($form_data[$arr_delete[$j]]);
				}				
			}
			for ($j	=	0;$j<count($term_arr_post);$j++)
			{
				$term	=	$term_arr_post[$j];
				$form_data[$term['name']]	=	$term['value'];
			}			
			
			$response = $browser->post($action, $form_data);
			
			if (preg_match('/<div\s*class="messages error">(.*?)<\/div>/ism',$response,$match)) {
				$page_mess	=	preg_replace('/<a[^>]*>.*?<\/a>/','',$match[1]);
				$page_mess	=	preg_replace('/<p[^>]*>.*?<\/p>/','',$page_mess);
				$this->setError('[CMS DRUPAL] #1 Fail to post content '."\r\n\t\t: message error $page_mess."."\r\n Link: ".$obj_article->link." Title: ".$obj_article->title);
				return false;
			}
			
			$db_drupal	=	$this->getDBO();
			$query		=	'SELECT  NR.*
								FROM `#__node` as N,`#__node_revisions` as NR 
								WHERE	N.vid=NR.vid
									and NR.body like '.$db_drupal->Quote('%'.$code_body);
			$db_drupal->setQuery($query);			
			$obj_node_revisions	=	$db_drupal->loadObject();
			if ($obj_node_revisions==null) {
				$this->setError('[CMS DRUPAL] Fail to post content. Content not found width title: '.$form_data['title']);
				$sdb	=	JRequest::getInt('showdebug',0);
				if ($sdb) {
					echo '<br /><hr />';
					echo '<br /><hr />';
					echo '<br /><hr />';
					echo $db_drupal->getQuery();
					echo '<br /><hr />';
					var_dump($form_data);
					echo '<br /><hr />';
					echo $response;
				}
				return false;
				
			}
		$obj_node_revisions->body	=	$obj_article->full_text;
		return $obj_node_revisions;
	}			

	// update to yos_content_link
	private function _added_fetched_article($link, $row){
		$db		=&	JFactory::getDBO();
		$query	=	"INSERT INTO #__yos_content_link SET
			`link`	=	".$db->Quote($link).", 
			`title`	=	".$db->Quote($row->title).", 
			`cms`	=	".$db->Quote('drupal').", 
			`articleid`	= $row->nid";
		$db->setQuery($query);
		$db->query();
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS DRUPAL] Fail to insert fetched article to list: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		$time_now		= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
		$fp = fopen( JPATH_COMPONENT_SITE.DS.'cms'.DS.'drupalpost'.DS.'log_article.txt', 'a');
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "--------------------------------------------------\r\n");
			fputs($fp, "------Run time: $time_now ------\r\n");
			fputs($fp, "------Title: $row->title ------\r\n");
			fputs($fp, "------NID: $row->nid ------\r\n");
			fputs($fp, "------Link: $link ------\r\n");			
			fclose($fp);
		return true;
	}

}